﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace saimawebclient
{
    public class CustomAuthorzieAttribute:AuthorizeAttribute
    {
        private string _controllerName = string.Empty;
        private string _actionName = string.Empty;

        /// <summary>
        /// base.OnAuthorization(filterContext)中会调用AuthorizeCore函数
        /// 
        /// 当AuthorizeCore返回false，则会继续调用HandleUnauthorizedRequest进行处理
        /// 
        /// 所以OnAuthorization是该类的总入口
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            _controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            _actionName = filterContext.ActionDescriptor.ActionName;

            base.OnAuthorization(filterContext);
        }

        /// <summary>
        /// base.OnAuthorization来调用
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (_controllerName.ToLower() == "show")
            {//登陆界面，不用身份认证，直接返回true
                return true;
            }

            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 当AuthorizeCore返回false时候调用
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }

    }
}